import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import './index.scss'
import { useEffect, useState } from 'react'
import { publishApi, getArticleDetail, editpublishApi } from '@/apis/article'
import { useChannel } from '@/hooks/useChannel'

const { Option } = Select
const Publish = () => {
  const [params] = useSearchParams()
  const { channelsList } = useChannel()

  const navigate = useNavigate()

  // 发布文章
  const pushishFinish = async (formValue) => {
    console.log('formValue');
    console.log(formValue);
    if (imgeList.length !== imageType) {
      message.warning('封面图和上传图片不一致')
      return
    }
    const { title, content, channel_id } = formValue
    const images = imgeList.map((item) => {
      if (item.response) {
        return item.response.data.url
      } else {
        return item.url
      }
    })
    const params = {
      title,
      content,
      cover: {
        type: imageType,
        images: images
      },
      channel_id
    }

    if (articleId) {
      const res = await editpublishApi(articleId, params)
      message.success('修改成功')
      navigate('/article')
    } else {
      const res = await publishApi(params)
      message.success('提交成功')
      navigate('/article')
    }


  }
  const [imgeList, setImageList] = useState([])
  //上传中回调
  const uploadChange = (files) => {
    console.log('files');
    console.log(files);
    setImageList(files.fileList)
  }
  // 切换图片类型
  const [imageType, setImgageType] = useState(1)
  const typeChange = (e) => {
    setImgageType(e.target.value)
  }
  // 回填数据
  const [form] = Form.useForm()
  const articleId = params.get('id')
  useEffect(() => {
    async function getDetail() {
      const res = await getArticleDetail(articleId)
      const data = res.data
      const { cover } = data
      form.setFieldsValue({
        ...data,
        type: cover.type
      })
      setImgageType(cover.type)
      setImageList(cover.images.map((item) => {
        return {
          url: item
        }
      }))
    }
    if (articleId) {
      getDetail()
    }
  }, [])
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb separator=">"
            items={[

              {
                href: '',
                title: (
                  <>
                    <span>首页</span>
                  </>
                ),
              },
              {
                title: `${articleId ? '编辑文章' : '新增文章'}`,
              },
            ]}
          >
            {/* <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>发布文章</Breadcrumb.Item> */}
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          onFinish={pushishFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {
                channelsList.map((item) => <Option value={item.id} key={item.id}>{item.name}</Option>)
              }
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={typeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {/* listType 文件外框样式 showUploadList：显示上传列表 */}
            {
              imageType !== 0 &&
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action={'http://geek.itheima.net/v1_0/upload'}
                onChange={uploadChange}
                maxCount={imageType}
                fileList={imgeList}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            }
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            className='publish-quil'
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill className='publish-quil' theme='snow' placeholder='请输入文章内容' />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发布文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish